#include "pthread.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "unistd.h"

typedef struct msg {
	char buf[256];
	int num;	
	pthread_t mutex;
	pthread_cond_t cond;
}MSG;

static MSG pkg;


static void *thread_out(void *arg)
{
	int i;


	
	while(1) {
		pthread_mutex_lock(&pkg.mutex);

		for(i = 0; i < pkg.num; i++) {
				if(pkg.buf[i] > 'A' && pkg.buf[i] < 'Z') {
				pkg.buf[i] = pkg.buf[i] + 32;
			}
		}

		printf("LAST: %s\n", pkg.buf);

		memset(pkg.buf, '\0', sizeof(pkg.buf));
		pkg.num = 0;

		pthread_cond_wait(&pkg.cond, &pkg.mutex);
		pthread_mutex_unlock(&pkg.mutex);
	}



}


static void *thread_in(void *arg)
{
	char ch;

	

	while(1) {
		pthread_mutex_lock(&pkg.mutex);
		ch = getc(stdin);
		// printf("ch=%x\n", ch);

		pkg.buf[pkg.num++] = ch;

		if(ch == 0x0a) {
			//printf("buf: %s\n", pkg.buf);
			pthread_cond_signal(&pkg.cond);
		}

		pthread_mutex_unlock(&pkg.mutex);
	}

	

}


int main(int argc, char const *argv[])
{
	pthread_t ph_in, ph_out;
	int ret;

	memset(pkg.buf, '\0', sizeof(pkg.buf));
	pkg.num = 0;

	pthread_mutex_init(&pkg.mutex, NULL);
	pthread_condattr_init(&pkg.cond);

	ret = pthread_create(&ph_in, NULL, (void *)thread_in, NULL);
	if(ret) {
		printf("ph_in err\n");
		exit(1);
	}

	ret = pthread_create(&ph_out, NULL, (void *)thread_out, NULL);
	if(ret) {
		printf("ph_out err\n");
		exit(1);
	}

	while(1) {
	    ;
	}

	// pthread_join(ph_in, NULL);
	// pthread_join(ph_out, NULL);


	return 0;
}


